#!/usr/bin/env python3
# -*- coding:utf-8 -*-

import os
import sys
import requests
from urllib.parse import unquote

current_dir = os.path.abspath(os.path.dirname(__file__))
rootPath = os.path.split(current_dir)[0]
sys.path.append(rootPath)
from flask import Flask, request, send_from_directory, Response
from utils import date_util, doc_util, html_util, read_config as readconfig
from service import users_service, get_all_stock_info
from service.data_service import stock_dict
from methods import a均线macd历史验证1 as ave_macd_v
from webs.service import web_service, start_stop_service
from app import git_service

app = Flask(__name__)
BASE_PATH = os.path.dirname(os.path.abspath(__file__))
result_path = os.path.join(readconfig.data_path, 'result', '突破均线')
p_name = 'main_web'

user_code_list = ['t1qznXH', 'tmPWfLK']


@app.route('/index', methods=['get'])
def index():
    try:
        usercode = request.cookies['usercode']
    except:
        usercode = ''
    return index_html(usercode)


def index_html(usercode):
    web = ''
    if usercode == '':
        web += html_util.get_a_text('<<登录注册>>')
        row_name_dict = {'用户编码': 'usercode'}
        web += html_util.get_form('/user/login', 'post', 'myForm12', row_name_dict, '登录注册')
    else:
        web += html_util.get_title('本网站只对数据进行监控,不构成任何投资建议')
        web += '</br>'
        web += html_util.get_title('用户:' + usercode)
        web += '</br>'
        web += html_util.get_form('/user/logout', 'post', 'myForm11', {}, '退出登录')
    web += html_util.get_a_text('<<添加监控代码>>')
    row_name_dict = {'股票编码': 'stockcode'}
    web += html_util.get_form('/task1/add', 'post', 'myForm1', row_name_dict, '添加')

    # 查询定时任务跑批触发记录结果
    web += html_util.get_a_text('<<查询日期监控触发记录>>')
    row_dict = {'日期': {'value': date_util.get_date_str(), 'name': 'date'}}
    web += html_util.get_form_has_value('/task1/trigger/result', 'post', '定时任务跑批结果', row_dict, '点击查询')

    # 查询指定日期仓位情况
    web += html_util.get_a_text('<<查询监控股票触发情况>>')
    web += html_util.get_form_has_value('/task1/position/result', 'post', '仓位情况', {}, '点击查询')

    # 查询当前所有监控代码
    web += html_util.get_a_text('<<查询当前监控股票>>')
    web += html_util.get_form_has_value('/monitor/stock/all', 'post', '监控代码', {}, '点击查询')

    web += html_util.get_a_text('<<历史数据分析验证页面>>')
    web += html_util.get_form_has_value('/analysis/index', 'post', '跳转', {}, '跳转')

    if user_code_list.__contains__(usercode):
        # 管理所有代码
        web += html_util.get_a_text('<<管理所有代码>>')
        # row_dict = {'密码': {'value': '123456', 'name': 'password'}}
        web += html_util.get_form_has_value('/stock/all', 'post', '管理所有代码', {}, '点击查询')

        # 查询定时任务跑批触发记录结果
        web += html_util.get_a_text('<<查询所有触发情况>>')
        row_dict = {'日期': {'value': date_util.get_date_str(), 'name': 'date'}}
        web += html_util.get_form_has_value('/task1/pool/result', 'post', '定时任务跑批结果', row_dict, '点击查询')

        # 管理后台
        web += html_util.get_a_text('<<管理后台>>')
        # row_dict = {'密码': {'value': '123456', 'name': 'password'}}
        web += html_util.get_form_has_value('/background/index', 'post', '管理后台', {}, '点击跳转')

    # web += ' <text>上传用户配置文件</text>'
    # web += '<form action="/upload/user" method="post" enctype="multipart/form-data">' \
    #        '<input type="file" id="img" name="img">' \
    #        '<button type="submit">用户配置文件上传</button></form>'
    return web


# 分析验证页面
@app.route("/analysis/index", methods=["post"])
def analysis_index():
    web = ''
    web += html_util.get_a_text('<<验证历史数据(均线+macd)>>')
    row_name_dict = {'股票编码': 'code', '验证长度': 'size'}
    web += html_util.get_form('/validation/m1', 'post', 'myForm3', row_name_dict, '验证')

    web += html_util.get_a_text('<<验证月macd(上穿0轴)>>')
    row_dict = {'日期': {'value': date_util.get_date_str(), 'name': 'date'}}
    web += html_util.get_form_has_value('/validation/m2', 'post', 'myForm4', row_dict, '验证所有')
    return web


# 管理后台首页
@app.route("/background/index", methods=["post"])
def background_index():
    # 重新启动按钮
    restart_url = 'http://' + readconfig.domain + '/restart/index/'
    web = html_util.get_button_href(restart_url, '重启')
    web += '<br>'
    web += '<br>'

    # 代码提交
    push_url = 'http://' + readconfig.domain + '/git/push'
    web += html_util.get_button_href(push_url, '代码提交')
    web += '<br>'
    web += '<br>'

    # 代码更新
    pull_url = 'http://' + readconfig.domain + '/git/pull'
    web += html_util.get_button_href(pull_url, '代码更新')
    web += '<br>'
    web += '<br>'

    # 查看当前task list
    url = 'http://' + readconfig.domain + '/get/task/pid'
    web += html_util.get_button_href(url, '查看当前taskPid')
    web += '<br>'
    web += '<br>'

    # 更新所有代码
    pull_url = 'http://' + readconfig.domain + '/stock/all/update'
    web += html_util.get_button_href(pull_url, '更新所有股票')
    web += '<br>'
    web += '<br>'

    # 下载文档文件
    web += html_util.get_a_text('下载文档文件')
    row_dict = {'文档路径': {'value': readconfig.data_path, 'name': 'path'}}
    web += html_util.get_form_has_value('/download/doc', 'post', '下载文档文件', row_dict, '查看')
    web += '<br>'

    # 代码远端同步
    web += html_util.get_a_text('同步远端代码')
    row_dict = {'代码分支': {'value': 'master', 'name': 'branch'}}
    web += html_util.get_form_has_value('/git/reset', 'post', '同步远端代码', row_dict, '同步')

    # 关机
    restart_url = 'http://' + readconfig.domain + '/restart/stop/' + p_name
    web += html_util.get_button_href(restart_url, '关机')
    web += '<br>'
    web += '<br>'

    web += '<br>'
    return web


# 上传用户信息
@app.route('/upload/user', methods=['post'])
def upload_user():
    fname = request.files['img']  # 获取上传的文件
    if fname:
        return users_service.add_users(fname)
    else:
        return '{"msg": "请上传文件！"}'


# 均线和 macd 验证
@app.route("/validation/m1", methods=["post"])
def validation_code_post():
    code = request.form['code']
    size = request.form['size']
    return validation_code(code, size)


# 月macd上穿0轴验证
@app.route("/validation/m2", methods=["post"])
def validation_m2_post():
    date = request.form['date']
    return web_service.month_validation(date)


# 均线和 macd 验证
# http://tashanzhishi.natapp1.cc/validation/m1/600559/80
@app.route("/validation/m1/<code>/<size>", methods=["GET"])
def validation_code(code, size):
    size = int(size)
    if size > 100:
        return '最大支持100以内'
    name = stock_dict[code]['name']
    stock_list = [{'code': code, 'name': name}]
    file_name = name + '-' + code
    file_path = os.path.join(result_path, date_util.get_date_str(), '历史验证数据', '验证', file_name + '.xlsx')
    if not os.path.exists(file_path):
        ave_macd_v.monitor_up_down(stock_list, 100)
    url = 'http://' + readconfig.domain + '//download/validation1/' + file_name + '.xlsx'
    return '<a href="' + url + '"> <button>' + file_name + '</button> </a>'


# 获取验证历史数据结果
@app.route("/download/validation1/<filename>", methods=["GET"])
def download_file(filename):
    dir = os.path.join(result_path, date_util.get_date_str(), '历史验证', '验证')
    return send_from_directory(dir, filename, as_attachment=True)


# 下载路径中文档
@app.route("/download/doc", methods=["post"])
def download_doc_get_path():
    path = request.form['path']  # 获取上传的文件
    # path = path.replace('&', '\\')
    if not os.path.exists(path):
        return '不存在路径'
    return web_service.file_path_names(path)


# 下载路径中文档
@app.route("/download/doc/<path>", methods=["GET"])
def download_doc_file(path):
    path = unquote(path, encoding="utf8")
    names = path.split('*')
    doc_path = ''
    for name in names[0:len(names) - 1]:
        if name == '':
            name = '/'  # linux 系统会出现
        doc_path = os.path.join(doc_path, name)
    print(doc_path)
    return send_from_directory(doc_path, names[-1], as_attachment=True)


# 下载路径中文档
@app.route("/get/task/pid", methods=["GET"])
def get_task_pid():
    pid_list = start_stop_service.get_pid('python')
    return pid_list


# 获取当天的跑批数据 均线 + macd
@app.route("/record/task1/<date>", methods=["GET"])
def get_task_result(date):
    file_path = os.path.join(result_path, date, '触发记录')
    file_list = doc_util.get_file_path_names(file_path)
    web = ''
    for file_name in file_list:
        file_name = file_name.replace('/', '\\')
        names = file_name.split('\\')
        file_name = names[-2] + '\\' + names[-1]
        url = 'http://' + readconfig.domain + '//download/validation1/' + file_name + '.xlsx'
        web += '<a href="' + url + '"> <button>' + file_name + '</button> </a>'
    return web


# 获取验证历史数据结果
@app.route("/download/task1/<date>/<filename>", methods=["GET"])
def download_file_task1(date, filename):
    filename = filename.replace('/', '\\')
    names = filename.split('\\')
    dir = os.path.join(result_path, date, '触发记录', names[0])
    return send_from_directory(dir, names[1], as_attachment=True)


# 增加监控股票 post请求
@app.route("/task1/add", methods=["post"])
def task1_add_code_post():
    try:
        usercode = request.cookies['usercode']
    except:
        resp = Response('请先进行登录')
        return resp
    stockcode = request.form['stockcode']  # 获取上传的文件
    if stockcode == '':
        resp = Response('代码编号为空')
        return resp
    return users_service.add_stock_code(usercode, stockcode)


# 用户登录
@app.route("/user/login", methods=["post"])
def user_login():
    try:
        usercode = request.form['usercode']
        resp = Response(index_html(usercode))
        resp.set_cookie('usercode', usercode, max_age=100000)
    except:
        resp = Response('请先进行登录')
    return resp


# 用户取消登录
@app.route("/user/logout", methods=["post"])
def user_logout():
    try:
        usercode = request.cookies['usercode']
        resp = Response(index_html(''))
        resp.set_cookie('usercode', usercode, max_age=0)
    except:
        resp = Response('请先进行登录')
    return resp


# 增加监控股票
@app.route("/task1/add/<usercode>/<stockcode>", methods=["GET"])
def task1_add_code(usercode, stockcode):
    return users_service.add_stock_code(usercode, stockcode)


# 删除监控股票
@app.route("/task1/del", methods=["post"])
def task1_del_code_post():
    usercode = request.form['usercode']  # 获取上传的文件
    stockcode = request.form['stockcode']  # 获取上传的文件
    return users_service.del_stock_code(usercode, stockcode)


# 删除监控股票
@app.route("/task1/del/<usercode>/<stockcode>", methods=["GET"])
def task1_del_code(usercode, stockcode):
    return users_service.del_stock_code(usercode, stockcode)


# 展示当日的结果
@app.route('/index1', methods=['get'])
def web1():
    htmls = doc_util.get_path_doc_info(os.path.join(readconfig.data_path, 'webs', 'index.html'))
    web = ''
    for h in htmls:
        web += h + '\n'
    return web


# 获取验证历史数据结果
@app.route("/download/validation1/<filename>", methods=["GET"])
def download_all_file(filename):
    dir = os.path.join(result_path, date_util.get_date_str(), '历史验证数据', '验证')
    return send_from_directory(dir, filename, as_attachment=True)


# 展示指定日期的跑批结果
@app.route("/task1/trigger/result", methods=["post"])
def task_trigger_result():
    return web_service.trigger_result(request.form['date'])


# 查询最近30天的情况
@app.route("/download/trigger1/<date>/<filename>", methods=["GET"])
def download_trigger1_file(date, filename):
    names = filename.split('*')
    code = names[1].split('-')[1].split('.')[0]
    return web_service.get_trigger_info(date, code)


# 查询最近30天的情况
@app.route("/download/position/<date>/<filename>", methods=["GET"])
def download_position_file(date, filename):
    names = filename.split('*')
    code = names[1].split('--')[0].split(':')[1]
    return web_service.get_trigger_info(date, code)


# 展示指定日期的仓位情况
@app.route("/task1/position/result", methods=["post"])
def task_position_result():
    try:
        usercode = request.cookies['usercode']
    except:
        usercode = ''
    return web_service.position_result(usercode, date_util.get_date_str())


# 展示指定日期的仓位情况
@app.route("/task1/pool/result", methods=["post"])
def task_pool_result():
    date = request.form['date']
    return web_service.position_result('', date)


# 获取用户编码
@app.route("/user/getcode", methods=["post"])
def user_getcode():
    password = request.form['password']
    if not os.path.exists(os.path.join(readconfig.data_path, 'webs', 'users', password)):
        return '密码错误'
    else:
        return doc_util.get_file_names(os.path.join(readconfig.data_path, 'webs', 'users', password))[0]


# 设置用户密码
@app.route("/user/setpassword", methods=["get"])
def user_setpassword():
    usercode = request.form['usercode']
    password = request.form['password']
    if usercode != '' and password != '':
        password_list = doc_util.get_file_names(os.path.join(readconfig.data_path, 'webs', 'users'))
        for pw in password_list:
            if password == pw:
                return '密码不可用'
        doc_util.gen_new_doc(os.path.join(readconfig.data_path, 'webs', 'users'), password + usercode, [usercode])
    return 'success'


# 提交代码
@app.route("/git/push", methods=["get"])
def git_push_service():
    msg = git_service.git_push('后台提交代码')
    return msg


# 更新代码
@app.route("/git/pull", methods=["get"])
def git_pull_service():
    msg = git_service.git_pull()
    return msg


# 提交代码
@app.route("/git/reset", methods=["post"])
def git_reset_service():
    branch = request.form['branch']
    msg = git_service.git_reset(branch)
    return msg


# 当前用户监控代码
@app.route("/monitor/stock/all", methods=["post"])
def monitor_stock_all():
    try:
        usercode = request.cookies['usercode']
    except:
        resp = Response('请先进行登录')
        return resp
    monitor_dict = users_service.get_all_monitor(usercode)
    row_dict = {}
    for stock in monitor_dict[usercode]:
        code = stock['code']
        name = stock['name']
        url = 'http://' + readconfig.domain + '/task1/del/' + usercode + '/' + code
        row_dict[code] = {'title': name + '-' + code, 'url': url, 'button': '删除' + name}
    return html_util.get_form_list_has_button(usercode + '的监控代码', row_dict)


# 所有代码
@app.route("/stock/all", methods=["post"])
def stock_all():
    s_dict = users_service.get_all_stock()
    for key in s_dict:
        value = s_dict[key]
        for stock in value.keys():
            code = value[stock]['code']
            name = value[stock]['name']
            button = '添加监控'
            if key == '监控中':
                button = '删除监控'
                url = 'http://' + readconfig.domain + '/task1/monitor/del/' + code
            else:
                url = 'http://' + readconfig.domain + '/task1/monitor/add/' + code
            value[code] = {'title': name + '-' + code, 'url': url, 'button': button + name}
        s_dict[key] = value
    return html_util.get_form_list_has_button('所有的股票代码', s_dict)


# 提交代码
@app.route("/task1/monitor/del/<code>", methods=["get"])
def task1_monitor_del_service(code):
    return users_service.monitor_del(code)


# 提交代码
@app.route("/task1/monitor/add/<code>", methods=["get"])
def task1_monitor_add_service(code):
    return users_service.monitor_add(code)


# 提交代码
@app.route("/stock/all/update", methods=["get"])
def update_stock_all():
    return get_all_stock_info.url_shen_shang()


# 重新启动按钮
@app.route("/restart/index", methods=["get"])
def restart_index():
    return requests.get('http://127.0.0.1:8888/restart/index')


# 重新启动按钮
@app.route("/restart/stop/<password>", methods=["get"])
def restart_stop_service(password):
    if password != readconfig.sys_password:
        return "密码错误"
    return requests.get('http://127.0.0.1:8888/restart/stop/' + p_name)


def run():
    print('开始记录线程')
    flag = start_stop_service.record_pid(p_name)
    print('结束记录线程')
    if flag == 1:
        app.run(host='0.0.0.0', port=8421)
        print('结束记录线程')


if __name__ == "__main__":
    print('')
    run()
